import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'

// loadinging
import * as loadinging from './api-config-loading'

// department config
import ds from './ds/api-config'
import gc from './gc/api-config'
import kg from './kg/api-config'
import pt from './pt/api-config'
import sw from './sw/api-config'
import tz from './tz/api-config'
import za from './za/api-config'
let alldepartment = { ds, gc, kg, pt, sw, tz, za }
let department

// defined data type
let dataType = {
    plain: 'text/plain',
    json: 'application/json',
    form: 'multipart/form-data',
    urlencoded: 'application/x-www-form-urlencoded'
}

// Request type defined
let Request = {}
let http = {}

// request interceptor
axios.interceptors.request.use(config => {
    if (config.loading && Vue.prototype.$ELEMENTRX.loading) {
        loadinging.showFullScreenLoading()
    }
    return config
}, error => {
    return Promise.reject(error)
})

// response interceptor
axios.interceptors.response.use(response => {
    if (response.config.loading && Vue.prototype.$ELEMENTRX.loading) {
        loadinging.tryHideFullScreenLoading()
    }
    return response
}, error => {
    if (Vue.prototype.$ELEMENTRX.loading) {
        loadinging.tryHideFullScreenLoading()
    }
    return Promise.reject(error)
})

// processing parameters
let request = options => {
    // 额外的参数配置处理
    let extra = {
        headers: options.extras.headers || {},
        loading: options.extras.loading === false ? undefined : true,
        dataType: options.extras.dataType || 'urlencoded',
        timeout: 100000
    }
    // 如果没有设置 Content-Type 设置发送给服务器的数据格式
    if (!extra.headers['Content-Type']) {
        extra.headers['Content-Type'] = dataType[extra.dataType] || extra.dataType
    }
    // 如果是POST请求 && urlencoded 需要转码
    if (typeof options.body === 'object' && extra.dataType === 'urlencoded') {
        options.body = qs.stringify(options.body)
    }
    // return new axiso request
    return axios.request({
        headers: extra.headers,
        url: options.action,
        method: options.method,
        data: options.body,
        params: options.params,
        timeout: extra.timeout,
        emulateJSON: true,
        loading: extra.loading
    })
}

// defined restful api forEach
['get', 'post', 'put', 'delete'].forEach(method => {
    http[method] = (
        action,
        params,
        type,
        extras = {}
    ) => {
        // 获取部门信息
        if (department === undefined) {
            try {
                let departmenttype = Vue.prototype.$ELEMENTRX.department
                if (!departmenttype) {
                    // eslint-disable-next-line
                    alert('部门ID未设置，请紧急联系前端解决')
                    return false
                }
                department = alldepartment[departmenttype]
            } catch (e) {
                // eslint-disable-next-line
                alert('部门ID未设置，请紧急联系前端解决')
                return false
            }
        }
        // 判断环境变量 获取正确的正式/测试
        if (process.env.NODE_ENV === 'development' || process.env.NODE_TEST === 'development') {
            action = department.development[type] + action
        } else {
            action = department.production[type] + action
        }
        // 处理传入参数配置 && 返回 axios 实例
        if (method === 'get') {
            return request({
                action,
                params,
                method,
                extras
            })
        } else {
            return request({
                action,
                body: params,
                method,
                extras
            })
        }
    }
})

Request.http = http

export default Request
